<template>
  <div class="multi-round-qa-page">
    <!-- 顶部 BossHeader -->
    <BossHeader />
    
    <div class="qa-container">
      <!-- 左侧历史记录 -->
      <div class="history-sidebar">
        <div class="history-header">
          <h3>对话历史</h3>
          <button class="new-chat-btn" @click="startNewChat" :disabled="isCreatingNewChat">
            <i v-if="!isCreatingNewChat" class="plus-icon"></i>
            <div v-else class="loading-spinner-small"></div>
            <span>{{ isCreatingNewChat ? '创建中...' : '新建对话' }}</span>
          </button>
        </div>
        <div class="history-list">
          <div v-if="isLoadingSessions" class="loading-sessions">
            <div class="loading-spinner"></div>
            <span>加载会话列表中...</span>
          </div>
          <div v-else>
            <div 
              v-for="chat in chatHistory" 
              :key="chat.id"
              class="history-item"
              :class="{ active: currentChatId === chat.id }"
              @click="selectChat(chat.id)"
            >
              <div class="chat-title">{{ chat.title }}</div>
              <div class="chat-time">{{ formatTime(chat.lastTime) }}</div>
              <div class="chat-preview">{{ chat.preview }}</div>
            </div>
            <div v-if="chatHistory.length === 0" class="empty-history">
              暂无对话历史
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧对话区域 -->
      <div class="chat-area">
        <div class="chat-header">
          <h2>智能多轮问答助手</h2>
          <p class="chat-subtitle">支持连续对话，能够理解上下文，为您提供更准确的求职指导</p>
        </div>

              <div class="chat-messages" ref="messagesContainer">
        <div v-if="isLoadingMessages" class="loading-messages">
          <div class="loading-spinner"></div>
          <span>加载消息中...</span>
        </div>
        <div v-else-if="currentMessages.length === 0" class="welcome-message">
            <div class="welcome-content">
              <div class="welcome-icon">🤖</div>
              <h3>欢迎使用多轮问答系统</h3>
              <p>我可以记住我们的对话历史，为您提供连贯的咨询服务：</p>
              <div class="suggestion-tags">
                <span class="tag" @click="askSuggestion('我想了解软件开发岗位的面试流程')">面试流程</span>
                <span class="tag" @click="askSuggestion('帮我分析一下我的简历需要改进的地方')">简历优化</span>
                <span class="tag" @click="askSuggestion('我该如何准备技术面试？')">技术面试</span>
                <span class="tag" @click="askSuggestion('职业发展规划建议')">职业规划</span>
                <span class="tag" @click="askSuggestion('帮我生成一份简历')">生成简历</span>
              </div>
            </div>
          </div>

          <div 
            v-for="message in currentMessages" 
            :key="message.id"
            class="message-item"
            :class="{ 'user-message': message.type === 'user', 'ai-message': message.type === 'ai' }"
          >
            <div class="message-avatar">
              <div v-if="message.type === 'user'" class="user-avatar">👤</div>
              <div v-else class="ai-avatar">🤖</div>
            </div>
            <div class="message-content">
              <div class="message-text" :class="{ 'markdown-content': message.type === 'ai' }">
                <span v-if="message.type === 'user'" v-html="message.content"></span>
                <div v-else class="markdown-rendered" v-html="renderMarkdown(message.content)"></div>
              </div>
              <div class="message-actions" v-if="message.type === 'ai'">
                <button class="action-btn" @click="copyMessage(message.content)">
                  <i class="copy-icon"></i>
                  复制
                </button>
                <button class="action-btn" @click="retryMessage(message)">
                  <i class="retry-icon"></i>
                  重试
                </button>
              </div>
              <div class="message-time">{{ formatTime(message.time) }}</div>
            </div>
          </div>

          <div v-if="isTyping" class="message-item ai-message typing">
            <div class="message-avatar">
              <div class="ai-avatar">🤖</div>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input-area">
                      <div class="input-container">
            <textarea
              v-model="inputMessage"
              ref="messageInput"
              placeholder="请输入您的问题，我会结合前面的对话为您解答..."
              class="message-input"
              :disabled="isTyping"
              rows="1"
              @keydown.enter.prevent="handleEnter"
              @input="adjustTextareaHeight"
            ></textarea>
            <button 
              class="send-btn" 
              :disabled="!inputMessage.trim() || isTyping"
              @click="sendMessage"
            >
              <i class="send-icon"></i>
            </button>
          </div>
          <div class="input-tips">
            <span>按 Enter 发送，Shift + Enter 换行</span>
            <span class="context-tip">💡 支持多轮对话，我会记住上下文</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 简历生成弹框 -->
    <div v-if="showResumeModal" class="modal-overlay" @click="closeResumeModal">
      <div class="modal-container" @click.stop>
        <div class="modal-header">
          <h3>生成简历信息</h3>
          <button class="close-btn" @click="closeResumeModal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="expectedSalary">期望薪资:</label>
            <input
              id="expectedSalary"
              v-model="resumeForm.expectedSalary"
              type="text"
              placeholder="例如: 8-12K, 10-15K"
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label for="expectedCity">期望城市:</label>
            <input
              id="expectedCity"
              v-model="resumeForm.expectedCity"
              type="text"
              placeholder="例如: 北京, 上海, 深圳"
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label for="expectedPosition">期望岗位:</label>
            <input
              id="expectedPosition"
              v-model="resumeForm.expectedPosition"
              type="text"
              placeholder="例如: 前端工程师, Java开发工程师"
              class="form-input"
            />
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-modal-btn" @click="closeResumeModal">取消</button>
          <button class="submit-modal-btn" @click="submitResumeForm">生成简历</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted, computed } from 'vue'
import BossHeader from '@/components/BossHeader.vue'
import request from '@/utils/request.js'
import { marked } from 'marked'

// 响应式数据
const inputMessage = ref('')
const isTyping = ref(false)
const isStreaming = ref(false)
const currentChatId = ref(null)
const messagesContainer = ref(null)
const messageInput = ref(null)
const isLoadingSessions = ref(true)
const isCreatingNewChat = ref(false)
const isLoadingMessages = ref(false)

// 简历生成弹框相关
const showResumeModal = ref(false)
const resumeForm = reactive({
  expectedSalary: '',
  expectedCity: '',
  expectedPosition: ''
})

// 聊天历史
const chatHistory = reactive([])

// 当前对话消息
const currentMessages = ref([])

// 配置 marked
marked.setOptions({
  breaks: true, // 支持换行
  gfm: true, // 支持 GitHub Flavored Markdown
})

// 方法
// 渲染Markdown格式
const renderMarkdown = (text) => {
  if (!text) return ''
  try {
    // 先检查是否包含HTML标签
    const hasHtmlTags = /<[^>]*>/g.test(text)
    
    if (hasHtmlTags) {
      // 如果包含HTML标签，先保护HTML标签，然后处理Markdown
      const htmlPlaceholders = {}
      let placeholderIndex = 0
      
      // 保护HTML标签
      let processedText = text.replace(/<[^>]+>/g, (match) => {
        const placeholder = `__HTML_PLACEHOLDER_${placeholderIndex}__`
        htmlPlaceholders[placeholder] = match
        placeholderIndex++
        return placeholder
      })
      
      // 处理Markdown
      processedText = marked(processedText)
      
      // 恢复HTML标签
      Object.keys(htmlPlaceholders).forEach(placeholder => {
        processedText = processedText.replace(placeholder, htmlPlaceholders[placeholder])
      })
      
      return processedText
    } else {
      // 如果没有HTML标签，正常处理Markdown
      return marked(text)
    }
  } catch (error) {
    console.error('Markdown渲染失败:', error)
    return text // 如果渲染失败，返回原始文本
  }
}

// 清理Markdown格式符号
const cleanMarkdown = (text) => {
  if (!text) return ''
  
  return text
    // 移除粗体标记 **text** 或 __text__
    .replace(/\*\*(.*?)\*\*/g, '$1')
    .replace(/__(.*?)__/g, '$1')
    // 移除斜体标记 *text* 或 _text_
    .replace(/\*(.*?)\*/g, '$1')
    .replace(/_(.*?)_/g, '$1')
    // 移除代码块标记 ```code``` 或 `code`
    .replace(/```[\s\S]*?```/g, '[代码块]')
    .replace(/`(.*?)`/g, '$1')
    // 移除链接标记 [text](url)
    .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
    // 移除图片标记 ![alt](url)
    .replace(/!\[([^\]]*)\]\([^)]+\)/g, '[图片]')
    // 移除标题标记 # ## ### 等
    .replace(/^#{1,6}\s+/gm, '')
    // 移除列表标记 - * +
    .replace(/^[\s]*[-*+]\s+/gm, '• ')
    // 移除数字列表标记 1. 2. 等
    .replace(/^[\s]*\d+\.\s+/gm, '• ')
    // 移除引用标记 >
    .replace(/^>\s*/gm, '')
    // 移除分割线 --- 或 ***
    .replace(/^[-*]{3,}$/gm, '')
    // 移除多余的空白字符
    .replace(/\s+/g, ' ')
    .trim()
}

// 获取聊天会话列表
const fetchChatSessions = async () => {
  try {
    isLoadingSessions.value = true
    console.log('获取聊天会话列表...')
    const response = await fetch('http://localhost:8000/chat/get-chat-session/?user_id=1', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    console.log('聊天会话列表响应:', result)
    
    if (result.code === 1 && result.data) {
      // 清空现有历史
      chatHistory.splice(0, chatHistory.length)
      
      // 转换API数据格式为前端需要的格式
      result.data.forEach(session => {
        const chatItem = {
          id: session.sessionId,
          title: session.title || '新会话',
          preview: cleanMarkdown(session.lastMessage) || '暂无消息',
          lastTime: new Date(parseInt(session.lastMessageTime) || Date.now()),
          messages: [], // 消息会在选择会话时加载
          apiMessages: [], // API格式的消息历史
          status: session.status,
          userId: session.userId
        }
        chatHistory.push(chatItem)
      })
      
      console.log('聊天会话列表加载完成，共', chatHistory.length, '个会话')
      
      // 测试Markdown清理功能（可以在开发时查看效果）
      if (result.data.length > 0 && result.data[0].lastMessage) {
        console.log('原始消息:', result.data[0].lastMessage)
        console.log('清理后:', cleanMarkdown(result.data[0].lastMessage))
      }
    } else {
      console.error('获取聊天会话失败:', result.message)
    }
  } catch (error) {
    console.error('获取聊天会话列表失败:', error)
  } finally {
    isLoadingSessions.value = false
  }
}

const formatTime = (date) => {
  const now = new Date()
  const diff = now - date
  
  if (diff < 1000 * 60) return '刚刚'
  if (diff < 1000 * 60 * 60) return `${Math.floor(diff / (1000 * 60))}分钟前`
  if (diff < 1000 * 60 * 60 * 24) return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  return date.toLocaleDateString()
}

const selectChat = async (chatId) => {
  currentChatId.value = chatId
  const chat = chatHistory.find(c => c.id === chatId)
  if (!chat) return
  
  try {
    isLoadingMessages.value = true
    console.log('获取会话消息列表...', chatId)
    
    // 调用后台接口获取消息列表
    const response = await fetch('http://localhost:8000/chat/get-chat-message/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        session_id: chatId
      })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    console.log('获取消息列表响应:', result)
    
    if (result.code === 1 && result.data) {
      // 清空当前消息
      currentMessages.value = []
      
      // 转换API数据为前端格式并按时间排序
      const messages = result.data
        .sort((a, b) => a.create_time - b.create_time) // 按创建时间排序
        .map((msg, index) => ({
          id: msg.meesage_id || msg.message_id || Date.now() + index,
          type: msg.role === 'user' ? 'user' : 'ai',
          content: msg.content,
          time: new Date(msg.create_time || Date.now()),
          isStreaming: false
        }))
      
      currentMessages.value = messages
      
      // 更新聊天记录的消息缓存
      chat.messages = [...messages]
      
      // 更新API消息格式
      chat.apiMessages = result.data.map(msg => ({
        role: msg.role,
        content: msg.content,
        messageId: msg.meesage_id || msg.message_id,
        createTime: msg.create_time
      }))
      
      console.log('消息列表加载完成，共', messages.length, '条消息')
      
    } else {
      console.error('获取消息列表失败:', result.message)
      // 如果获取失败，使用本地缓存的消息（如果有）
      currentMessages.value = [...(chat.messages || [])]
    }
    
  } catch (error) {
    console.error('获取消息列表接口调用失败:', error)
    // 如果接口调用失败，使用本地缓存的消息（如果有）
    currentMessages.value = [...(chat.messages || [])]
  } finally {
    isLoadingMessages.value = false
  }
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}

const startNewChat = async () => {
  try {
    isCreatingNewChat.value = true
    console.log('创建新会话...')
    
    // 调用后端接口创建新会话
    const response = await fetch('http://localhost:8000/chat/create-chat/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        user_id: 1
      })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    console.log('创建新会话响应:', result)
    
    if (result.code === 1 && result.data && result.data.sessionId) {
      // 创建成功，创建新的聊天记录
      const newChat = {
        id: result.data.sessionId, // 使用后端返回的sessionId
        title: '新会话',
        preview: '暂无消息',
        lastTime: new Date(),
        messages: [],
        apiMessages: [],
        status: 'active',
        userId: '1'
      }
      
      // 添加到聊天历史的开头
      chatHistory.unshift(newChat)
      
      // 设置为当前会话
      currentChatId.value = result.data.sessionId
      currentMessages.value = []
      inputMessage.value = ''
      
      console.log('新会话创建成功，sessionId:', result.data.sessionId)
      
    } else {
      console.error('创建新会话失败:', result.message)
      // 显示错误提示（可以考虑添加toast提示）
      alert('创建新会话失败: ' + (result.message || '未知错误'))
    }
    
  } catch (error) {
    console.error('创建新会话接口调用失败:', error)
    // 显示错误提示
    alert('创建新会话失败，请检查网络连接')
  } finally {
    isCreatingNewChat.value = false
  }
}

const askSuggestion = (question) => {
  // 如果是生成简历的请求，显示弹框
  if (question === '帮我生成一份简历') {
    showResumeModal.value = true
    return
  }
  
  inputMessage.value = question
  sendMessage()
}

// 简历弹框相关方法
const openResumeModal = () => {
  showResumeModal.value = true
}

const closeResumeModal = () => {
  showResumeModal.value = false
  // 清空表单
  resumeForm.expectedSalary = ''
  resumeForm.expectedCity = ''
  resumeForm.expectedPosition = ''
}

const submitResumeForm = () => {
  // 验证表单
  if (!resumeForm.expectedSalary.trim() || !resumeForm.expectedCity.trim() || !resumeForm.expectedPosition.trim()) {
    alert('请填写完整的信息')
    return
  }
  
  // 组装消息内容
  const message = `帮我生成一份简历，我的期望薪资是${resumeForm.expectedSalary}，期望工作城市是${resumeForm.expectedCity}，期望岗位是${resumeForm.expectedPosition}`
  
  // 关闭弹框
  closeResumeModal()
  
  // 发送消息
  inputMessage.value = message
  sendMessage()
}

const handleEnter = (event) => {
  if (event.shiftKey) {
    return // 允许换行
  }
  sendMessage()
}

const adjustTextareaHeight = () => {
  const textarea = messageInput.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isTyping.value || isStreaming.value) return

  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: inputMessage.value.trim(),
    time: new Date()
  }

  const questionText = inputMessage.value.trim()

  // 如果是新对话，需要先创建会话
  if (!currentChatId.value) {
    console.error('没有当前会话ID，请先创建新会话')
    return
  }

  currentMessages.value.push(userMessage)
  inputMessage.value = ''
  
  nextTick(() => {
    adjustTextareaHeight()
    scrollToBottom()
  })

  // 显示输入状态
  isTyping.value = true

  try {
    // 创建AI消息占位符
    const aiMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: '',
      time: new Date(),
      isStreaming: false
    }
    currentMessages.value.push(aiMessage)
    
    // 调用发送消息接口
    console.log('发送消息到后台接口:', {
      url: 'http://localhost:8000/chat/send-chat/',
      user_id: 1,
      session_id: currentChatId.value,
      question: questionText
    })
    
    const response = await fetch('http://localhost:8000/chat/send-chat/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        user_id: 1,
        session_id: currentChatId.value,
        question: questionText
      })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    console.log('发送消息接口响应:', result)
    
    isTyping.value = false
    
    if (result.code === 1) {
      // 成功响应
      aiMessage.content = result.data.answer
      aiMessage.isStreaming = false
      
      // 获取当前聊天记录
      const currentChat = chatHistory.find(c => c.id === currentChatId.value)
      
      // 更新聊天历史
      if (currentChat) {
        // 构建API消息格式（用于显示历史记录）
        currentChat.apiMessages = []
        
        // 从messageList中构建消息历史
        if (result.data.messageList && result.data.messageList.length > 0) {
          result.data.messageList.forEach(msg => {
            currentChat.apiMessages.push({
              role: msg.role,
              content: msg.content,
              messageId: msg.meesage_id || msg.message_id,
              createTime: msg.create_time
            })
          })
        }
        
        currentChat.messages = [...currentMessages.value]
        currentChat.lastTime = new Date()
        // 更新预览文本，清理Markdown格式
        const cleanPreview = cleanMarkdown(result.data.answer)
        currentChat.preview = cleanPreview.slice(0, 30) + (cleanPreview.length > 30 ? '...' : '')
        
        // 更新标题（如果是第一条消息）
        if (currentMessages.value.length <= 2) { // 用户消息 + AI消息
          const cleanTitle = cleanMarkdown(questionText)
          currentChat.title = cleanTitle.slice(0, 15) + (cleanTitle.length > 15 ? '...' : '') || '新会话'
        }
      }
      
    } else {
      // 失败响应
      aiMessage.content = `❌ ${result.message || '请求失败，请稍后重试'}`
      aiMessage.isStreaming = false
    }
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
    
  } catch (error) {
    console.error('调用发送消息接口失败:', error)
    
    let errorContent = ''
    
    if (error.message.includes('fetch')) {
      errorContent = '🌐 网络连接出现问题，请检查您的网络连接后重试。'
    } else {
      errorContent = '❌ 出现了未知错误，请稍后重试。如果问题持续存在，请联系技术支持。'
    }
    
    // 更新AI消息为错误内容
    const messages = currentMessages.value
    const lastMessage = messages[messages.length - 1]
    if (lastMessage && lastMessage.type === 'ai') {
      lastMessage.content = errorContent
      lastMessage.isStreaming = false
    }
    
    // 更新聊天历史
    const currentChat = chatHistory.find(c => c.id === currentChatId.value)
    if (currentChat) {
      currentChat.messages = [...currentMessages.value]
      currentChat.lastTime = new Date()
      currentChat.preview = cleanMarkdown(errorContent).slice(0, 30) + '...'
    }
  } finally {
    isTyping.value = false
    
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const cancelStreaming = () => {
  // 由于现在是普通JSON响应，不需要取消流式输出
  isTyping.value = false
  isStreaming.value = false
  
  console.log('取消请求')
}

const copyMessage = async (content) => {
  try {
    // 复制原始的 Markdown 文本
    await navigator.clipboard.writeText(content)
    // 这里可以添加复制成功的提示
    console.log('消息已复制到剪贴板')
    
    // 可以考虑添加一个临时的成功提示
    // 例如显示一个 toast 消息
  } catch (err) {
    console.error('复制失败:', err)
  }
}

const retryMessage = (message) => {
  // 找到这条消息对应的用户消息
  const messageIndex = currentMessages.value.findIndex(m => m.id === message.id)
  if (messageIndex > 0) {
    const userMessage = currentMessages.value[messageIndex - 1]
    if (userMessage && userMessage.type === 'user') {
      inputMessage.value = userMessage.content
      sendMessage()
    }
  }
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 组件挂载时的初始化
onMounted(async () => {
  // 获取聊天会话列表
  await fetchChatSessions()
  
  // 默认选择第一个对话
  if (chatHistory.length > 0) {
    selectChat(chatHistory[0].id)
  }
})

// 在组件卸载时清理定时器
onUnmounted(() => {
  if (currentEventSource.value) {
    if (typeof currentEventSource.value.abort === 'function') {
      currentEventSource.value.abort()
    }
  }
})

</script>

<style scoped>
.multi-round-qa-page {
  min-height: 100vh;
  background: #f5f7fa;
}

.qa-container {
  display: flex;
  height: calc(100vh - 49px);
  margin-top: 49px;
}

/* 左侧历史记录 */
.history-sidebar {
  width: 320px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.history-header {
  padding: 24px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafbfc;
}

.history-header h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.new-chat-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #00BEBD 0%, #009a9a 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(0, 190, 189, 0.2);
}

.new-chat-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #009a9a 0%, #007d7d 100%);
  box-shadow: 0 4px 8px rgba(0, 190, 189, 0.3);
  transform: translateY(-1px);
}

.new-chat-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.loading-spinner-small {
  width: 16px;
  height: 16px;
  border: 2px solid #ffffff;
  border-top: 2px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.plus-icon::before {
  content: '+';
  font-size: 18px;
  font-weight: bold;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.history-item {
  padding: 16px;
  margin-bottom: 8px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
  background: #fff;
}

.history-item:hover {
  background: #f8f9fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transform: translateY(-1px);
}

.history-item.active {
  background: linear-gradient(135deg, #e6f9f9 0%, #d1f5f5 100%);
  border-color: #00BEBD;
  box-shadow: 0 2px 8px rgba(0, 190, 189, 0.15);
}

.chat-title {
  font-size: 15px;
  color: #303133;
  margin-bottom: 6px;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-preview {
  font-size: 13px;
  color: #909399;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-time {
  font-size: 12px;
  color: #c0c4cc;
}

.empty-history {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 60px 20px;
}

.loading-sessions {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #606266;
  font-size: 14px;
}

.loading-messages {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #606266;
  font-size: 14px;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e4e7ed;
  border-top: 2px solid #00BEBD;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 右侧对话区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.chat-header {
  padding: 24px 32px;
  border-bottom: 1px solid #e4e7ed;
  background: linear-gradient(135deg, #fff 0%, #fafbfc 100%);
}

.chat-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 22px;
  font-weight: 700;
}

.chat-subtitle {
  margin: 0;
  color: #606266;
  font-size: 15px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px 32px;
  background: #fafbfc;
}

.welcome-message {
  text-align: center;
  padding: 80px 20px;
}

.welcome-content {
  max-width: 600px;
  margin: 0 auto;
}

.welcome-icon {
  font-size: 64px;
  margin-bottom: 24px;
}

.welcome-content h3 {
  color: #303133;
  font-size: 28px;
  margin-bottom: 12px;
  font-weight: 700;
}

.welcome-content p {
  color: #606266;
  font-size: 16px;
  margin-bottom: 32px;
  line-height: 1.6;
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
}

.tag {
  padding: 10px 20px;
  background: linear-gradient(135deg, #e6f9f9 0%, #d1f5f5 100%);
  color: #00BEBD;
  border-radius: 25px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #00BEBD;
  box-shadow: 0 2px 4px rgba(0, 190, 189, 0.1);
}

.tag:hover {
  background: linear-gradient(135deg, #00BEBD 0%, #009a9a 100%);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 190, 189, 0.3);
}

.message-item {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin: 0 16px;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-avatar {
  background: linear-gradient(135deg, #00BEBD 0%, #009a9a 100%);
  color: white;
}

.ai-avatar {
  background: linear-gradient(135deg, #f0f2f5 0%, #e4e7ed 100%);
  color: #606266;
}

.message-content {
  max-width: 75%;
  min-width: 100px;
}

.user-message .message-content {
  text-align: right;
}

.message-text {
  background: #fff;
  padding: 16px 20px;
  border-radius: 16px;
  font-size: 15px;
  line-height: 1.6;
  color: #303133;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  white-space: pre-wrap;
  border: 1px solid #f0f0f0;
}

.user-message .message-text {
  background: linear-gradient(135deg, #00BEBD 0%, #009a9a 100%);
  color: white;
  border: none;
}

/* Markdown 渲染样式 */
.markdown-rendered {
  line-height: 1.6;
}

.markdown-rendered h1,
.markdown-rendered h2,
.markdown-rendered h3,
.markdown-rendered h4,
.markdown-rendered h5,
.markdown-rendered h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #303133;
}

.markdown-rendered h1 {
  font-size: 1.5em;
  border-bottom: 2px solid #e4e7ed;
  padding-bottom: 8px;
}

.markdown-rendered h2 {
  font-size: 1.3em;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 4px;
}

.markdown-rendered h3 {
  font-size: 1.2em;
}

.markdown-rendered p {
  margin: 8px 0;
}

.markdown-rendered ul,
.markdown-rendered ol {
  margin: 8px 0;
  padding-left: 20px;
}

.markdown-rendered li {
  margin: 4px 0;
}

.markdown-rendered blockquote {
  border-left: 4px solid #00BEBD;
  margin: 16px 0;
  padding: 8px 16px;
  background-color: #f8f9fa;
  color: #606266;
}

.markdown-rendered code {
  background-color: #f1f2f3;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
  color: #e83e8c;
}

.markdown-rendered pre {
  background-color: #f8f8f8;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  margin: 12px 0;
  overflow-x: auto;
}

.markdown-rendered pre code {
  background: none;
  padding: 0;
  color: #303133;
  font-size: 0.9em;
}

.markdown-rendered table {
  border-collapse: collapse;
  width: 100%;
  margin: 16px 0;
}

.markdown-rendered th,
.markdown-rendered td {
  border: 1px solid #e4e7ed;
  padding: 8px 12px;
  text-align: left;
}

.markdown-rendered th {
  background-color: #f5f7fa;
  font-weight: 600;
}

.markdown-rendered tr:nth-child(even) {
  background-color: #fafbfc;
}

.markdown-rendered strong {
  font-weight: 600;
  color: #303133;
}

.markdown-rendered em {
  font-style: italic;
  color: #606266;
}

.markdown-rendered a {
  color: #00BEBD;
  text-decoration: none;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
  display: inline-block;
  background: rgba(0, 190, 189, 0.1);
  border: 1px solid rgba(0, 190, 189, 0.2);
}

.markdown-rendered a:hover {
  text-decoration: none;
  background: #00BEBD;
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 190, 189, 0.3);
}

.markdown-rendered hr {
  border: none;
  border-top: 1px solid #e4e7ed;
  margin: 20px 0;
}

.message-text.streaming {
  position: relative;
}

.streaming-content {
  white-space: pre-wrap;
}

.streaming-cursor {
  display: inline-block;
  color: #00BEBD;
  font-weight: bold;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.message-actions {
  margin: 12px 0 8px 0;
  display: flex;
  gap: 8px;
}

.action-btn {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  color: #6c757d;
  padding: 6px 12px;
  border-radius: 18px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-btn:hover {
  background: #00BEBD;
  color: white;
  border-color: #00BEBD;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 190, 189, 0.2);
}

.copy-icon::before {
  content: '📋';
  font-size: 12px;
}

.retry-icon::before {
  content: '🔄';
  font-size: 12px;
}

.message-time {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 8px;
}

.user-message .message-time {
  text-align: right;
}

.typing {
  opacity: 0.8;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 16px 20px;
  background: #f0f2f5;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #909399;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  40% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 输入区域 */
.chat-input-area {
  padding: 24px 32px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 16px;
  margin-bottom: 12px;
}

.message-input {
  flex: 1;
  min-height: 48px;
  max-height: 120px;
  padding: 14px 20px;
  border: 2px solid #e4e7ed;
  border-radius: 24px;
  font-size: 15px;
  line-height: 1.5;
  resize: none;
  outline: none;
  font-family: inherit;
  transition: all 0.3s;
  background: #fafbfc;
}

.message-input:focus {
  border-color: #00BEBD;
  background: #fff;
  box-shadow: 0 0 0 3px rgba(0, 190, 189, 0.1);
}

.message-input:disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

.send-btn {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #00BEBD 0%, #009a9a 100%);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 190, 189, 0.3);
}

.send-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #009a9a 0%, #007d7d 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 190, 189, 0.4);
}

.send-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.cancel-btn {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #f56c6c 0%, #e54545 100%);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
}

.cancel-btn:hover {
  background: linear-gradient(135deg, #e54545 0%, #d73027 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.4);
}

.send-icon::before {
  content: '➤';
  font-size: 18px;
}

.cancel-icon::before {
  content: '✕';
  font-size: 18px;
  font-weight: bold;
}

.input-tips {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: #909399;
}

.context-tip {
  color: #00BEBD;
  font-weight: 500;
}

/* 滚动条样式 */
.history-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 简历生成弹框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
  animation: modalShow 0.3s ease-out;
}

@keyframes modalShow {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.modal-header {
  padding: 24px 24px 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
}

.modal-header h3 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.close-btn:hover {
  background: #f5f7fa;
  color: #606266;
  transform: rotate(90deg);
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group:last-child {
  margin-bottom: 0;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
  background: #fafbfc;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #00BEBD;
  background: #fff;
  box-shadow: 0 0 0 3px rgba(0, 190, 189, 0.1);
}

.form-input::placeholder {
  color: #c0c4cc;
}

.modal-footer {
  padding: 16px 24px 24px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.cancel-modal-btn,
.submit-modal-btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  min-width: 80px;
}

.cancel-modal-btn {
  background: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.cancel-modal-btn:hover {
  background: #e4e7ed;
  color: #303133;
}

.submit-modal-btn {
  background: linear-gradient(135deg, #00BEBD 0%, #009a9a 100%);
  color: white;
  box-shadow: 0 2px 4px rgba(0, 190, 189, 0.2);
}

.submit-modal-btn:hover {
  background: linear-gradient(135deg, #009a9a 0%, #007d7d 100%);
  box-shadow: 0 4px 8px rgba(0, 190, 189, 0.3);
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .history-sidebar {
    width: 280px;
  }
  
  .chat-messages,
  .chat-input-area {
    padding: 20px 24px;
  }
}

@media (max-width: 768px) {
  .qa-container {
    flex-direction: column;
  }
  
  .history-sidebar {
    width: 100%;
    height: 200px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .chat-messages,
  .chat-input-area {
    padding: 16px 20px;
  }
  
  .chat-header {
    padding: 20px;
  }
  
  .input-tips {
    flex-direction: column;
    gap: 4px;
    align-items: center;
  }

  .modal-container {
    width: 95%;
    margin: 20px;
  }
  
  .modal-header,
  .modal-body {
    padding: 20px;
  }
  
  .modal-footer {
    padding: 16px 20px 20px;
    flex-direction: column;
  }
  
  .cancel-modal-btn,
  .submit-modal-btn {
    width: 100%;
  }
}
</style>
